﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace System.Serialization
{
    public static partial class SerializationManager
    {
        /// <summary>
        /// JOSN 序列化[Json.net]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="this"></param>
        /// <returns></returns>
        public static byte[] JsonSerializer<T>(this T @this)
        {
            JsonSerializer jsonSerializer = Newtonsoft.Json.JsonSerializer.Create();
            using (var ms = new MemoryStream())
            {
                var writer = new StreamWriter(ms);
                var jsonWriter = new JsonTextWriter(writer);
                jsonSerializer.Serialize(jsonWriter, @this);
                return ms.GetBuffer();
            }
        }
        /// <summary>
        /// JSON反序列化[Json.net]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="this"></param>
        /// <returns></returns>
        public static T JsonDeSerializer<T>(this string @this)
        {
            return JsonConvert.DeserializeObject<T>(@this);
        }

        /// <summary>
        /// JSON反序列化[Json.net]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="this"></param>
        /// <returns></returns>
        public static T JsonDeSerializer<T>(this byte[] @this)
        {
            object deserializedValue;
            var jsonSerializer = Newtonsoft.Json.JsonSerializer.Create();
            using(var sr = new StreamReader(new MemoryStream(@this)))
            {
                JsonReader jsonReader = new JsonTextReader(sr);
                deserializedValue = jsonSerializer.Deserialize(jsonReader, typeof(T));
                if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
                {
                    throw new JsonSerializationException(
                        "Additional text found in JSON string after finishing deserializing object.");
                }
            }
            return (T) deserializedValue;
        }
    }
}
